package org.feng.controller;

import org.feng.entity.dto.StudentDTO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

/**
 * 学生控制器
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2022年06月11日 09时53分
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    private List<StudentDTO> students;

    /**
     * 查询所有的学生信息
     *
     * @return 学生列表
     */
    @GetMapping("/")
    public Flux<StudentDTO> listStudents() {
        return Flux.fromIterable(students);
    }

    /**
     * 通过学生ID查找目标学生
     *
     * @param id ID
     * @return 目标学生
     */
    @GetMapping("/{id}")
    public Mono<StudentDTO> searchStudentById(@PathVariable("id") Long id) {
        Optional<StudentDTO> student = students.stream()
                .filter(studentDTO -> Objects.equals(studentDTO.getId(), id))
                .findFirst();
        return Mono.just(student.orElseThrow(() -> new RuntimeException("找不到目标编号为 " + id + " 的学生")));
    }

    @PostConstruct
    private void initStudent() {
        char first = 'A' - 1;
        students = LongStream.rangeClosed(1, 7).boxed()
                .map(num ->
                        new StudentDTO(num, "100" + num, "学生" + ((char) (first + num)), ThreadLocalRandom.current().nextInt(18, 26))
                ).collect(Collectors.toList());
    }
}
